package com.apes.scm.masterdata.finance.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.finance.model.CooperateType;
import com.apes.scm.masterdata.finance.repository.CooperateTypeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Classname cooperateTypeService
 * @Description wsj
 * @Date 2020/1/10 14:09
 * @Created by Administrator
 */
@Service("cooperateTypeService")
public class CooperateTypeService extends DomainService {
    @Autowired
    private CooperateTypeRepository cooperateTypeRepository;


    public CooperateType save(SimpleRequest request) {
        CooperateType cooperateType = request.getO(CooperateType.class);
        CooperateType data = cooperateTypeRepository.findOne(JpaDsl.toCriteriaByEq("name",cooperateType.getName())).orElse(null);
        if (data != null) throw new RuntimeException("该保险公司" + cooperateType.getName() +"已存在系统,请勿重复定义!!!!");
        return cooperateTypeRepository.saveAndFlush(cooperateType);
    }


    /***
     * 功能： 修改
     * @param request
     * @return
     */
    public CooperateType update(SimpleRequest request) {
        checkData(request);
        CooperateType cooperateType = request.getO(CooperateType.class);
        return cooperateTypeRepository.saveAndFlush(cooperateType);
    }

    /***
     * 功能： 删除
     * @param request
     * @return
     * @throws RuntimeException
     */
    public String delete(SimpleRequest request) throws RuntimeException {
        checkData(request);
        CooperateType cooperateType = request.getO(CooperateType.class);
        cooperateTypeRepository.delete(cooperateType.getId());
        return "cooperateType";
    }


    private void checkData(SimpleRequest request) {
        String id = request.get("id");
        long versions = (int) request.get("version"); // 获取当前请求的版本信息
        CooperateType cooperateType = cooperateTypeRepository.findOne(id);
        if (cooperateType == null) throw new RuntimeException("保险公司【" + id + "】在系统中不存在。");
        if (cooperateType.getVersion() != versions) throw new RuntimeException("记录已更新或已删除，请重新提交！");  // 用于判断当前版本是否被修改
    }


    /**
     * 查询单个数据
     * @param request
     * @return
     */
    public CooperateType findOne(SimpleRequest request) {
        String id = request.get("id");

        CooperateType cooperateType = cooperateTypeRepository.findOne(id);

        if (cooperateType == null) throw new RuntimeException("合作类型：" + request.get("id") + " 在系统中不存在。");
        return cooperateType;
    }
}
